#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import threading
from elasticsearch import Elasticsearch
import click
import logging


logging.getLogger().setLevel(logging.INFO)
queries = []
mutex = threading.Lock()


@click.command()
@click.option('--host', help='elasticsearch host address', default='http://127.0.0.1:9200/',  required=1)
@click.option('--which', help='which one will be change? 0 for group_flag; 1 for cent_flag', default=0, required=1)
def main(host, which):
    process_group_data(host, which)


def select_by_group_flag(es, fields=None, offset=0, limit=0):
    for record in es.search(index="resultdb", doc_type="result",
                            body={'query': {'term': {'group_flag': 1}}}, _source_include=fields or [],
                            from_=offset, size=limit
                            ).get('hits', {}).get('hits', []):
        yield record['_source']


def select_by_cent_flag(es, fields=None, offset=0, limit=0):
    for record in es.search(index="resultdb", doc_type="result",
                            body={'query': {'term': {'cent_flag': 1}}}, _source_include=fields or [],
                            from_=offset, size=limit
                            ).get('hits', {}).get('hits', []):
        yield record['_source']


def modify_group_flag(es, resultid, group_flag):
    ret = es.update(index="resultdb", doc_type="result",
                    body={'doc': {'group_flag': group_flag}}, detect_noop=False, id=resultid)
    return ret


def modify_cent_flag(es, resultid, cent_flag):
    ret = es.update(index="resultdb", doc_type="result",
                    body={'doc': {'cent_flag': cent_flag}}, detect_noop=False, id=resultid)
    return ret


def process_group_data(host, which):
    offset = 0
    limit = 20
    resultes = Elasticsearch(hosts=host)
    while True:
        if which == 0:
            results = select_by_group_flag(resultes, offset=offset, limit=limit)
        else:
            results = select_by_cent_flag(resultes, offset=offset, limit=limit)
        results = list(results)
        nmatched = len(results)
        if nmatched == 0:
            break
        offset += nmatched
        for result in results:
            if not result:
                continue
            project = result['project']
            taskid = result['taskid']
            resultid = '%s:%s' % (project, taskid)
            if which == 0:
                modify_group_flag(resultes, resultid, 0)
            else:
                modify_cent_flag(resultes, resultid, 0)

if __name__ == '__main__':
    main()

